// 全局状态管理
let currentSessionId = null;
let sessions = [];
let currentConversations = [];

// DOM元素
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
const chatMessages = document.getElementById('chatMessages');
const historyList = document.getElementById('historyList');
const newChatBtn = document.querySelector('.new-chat-btn');
const viewMemoryBtn = document.querySelector('.sidebar-footer .view-memory');
const clearMemoryBtn = document.querySelector('.sidebar-footer .clear-memory');

// 初始化
document.addEventListener('DOMContentLoaded', async function() {
    // 绑定事件监听器
    sendBtn.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
    
    newChatBtn.addEventListener('click', createNewChat);
    viewMemoryBtn.addEventListener('click', viewMemory);
    clearMemoryBtn.addEventListener('click', clearMemory);
    
    // 加载会话列表
    await loadSessions();
    
    // 聚焦到输入框
    messageInput.focus();
    
    // 自动调整输入框高度
    messageInput.addEventListener('input', autoResizeTextarea);
    messageInput.addEventListener('keydown', handleKeyDown);
});

// 加载会话列表
async function loadSessions() {
    try {
        showLoading(historyList);
        const response = await SessionAPI.getSessions();
        
        if (response.code === 200) {
            sessions = response.data.sessions;
            renderSessionsList();
            
            // 如果没有当前会话且有会话列表，选择第一个
            if (!currentSessionId && sessions.length > 0) {
                await switchSession(sessions[0].session_id);
            }
        }
    } catch (error) {
        showError('加载会话列表失败: ' + error.message);
    }
}

// 渲染会话列表
function renderSessionsList() {
    if (sessions.length === 0) {
        historyList.innerHTML = '<div class="no-history">暂无聊天记录</div>';
        return;
    }
    
    historyList.innerHTML = sessions.map(session => `
        <div class="session-item ${session.session_id === currentSessionId ? 'active' : ''}" 
             data-session-id="${session.session_id}">
            <div class="session-info">
                <div class="session-title">${session.title}</div>
                <div class="session-time">${formatTime(session.updated_at)}</div>
            </div>
            <button class="delete-session-btn" onclick="deleteSession('${session.session_id}')">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    `).join('');
    
    // 绑定会话点击事件
    historyList.querySelectorAll('.session-item').forEach(item => {
        item.addEventListener('click', function(e) {
            if (!e.target.closest('.delete-session-btn')) {
                const sessionId = this.dataset.sessionId;
                switchSession(sessionId);
            }
        });
    });
}

// 切换会话
async function switchSession(sessionId) {
    try {
        currentSessionId = sessionId;
        
        // 更新UI状态
        document.querySelectorAll('.session-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-session-id="${sessionId}"]`)?.classList.add('active');
        
        // 清空聊天界面
        chatMessages.innerHTML = '';
        
        // 加载会话历史
        await loadConversations(sessionId);
        
        // 添加欢迎消息
        addMessage("Hi, 你好\n我是你的AI助手,有什么可以帮助你的吗?", 'ai');
        
        showNotification('已切换到新会话');
    } catch (error) {
        showError('切换会话失败: ' + error.message);
    }
}

// 加载对话历史
async function loadConversations(sessionId) {
    try {
        const response = await HistoryAPI.getConversations(sessionId);
        
        if (response.code === 200) {
            currentConversations = response.data.conversations;
            
            // 渲染历史对话
            currentConversations.forEach(conv => {
                addMessage(conv.user_input, 'user', conv.created_at);
                addMessage(conv.final_response, 'ai', conv.created_at);
            });
        }
    } catch (error) {
        console.error('加载对话历史失败:', error);
    }
}

// 创建新对话
async function createNewChat() {
    try {
        showLoading(chatMessages);
        
        const response = await SessionAPI.createSession();
        
        if (response.code === 200) {
            const newSession = response.data;
            sessions.unshift(newSession);
            currentSessionId = newSession.session_id;
            
            // 更新UI
            renderSessionsList();
            chatMessages.innerHTML = '';
            
            // 添加欢迎消息
            addMessage("Hi, 你好\n我是你的AI助手,有什么可以帮助你的吗?", 'ai');
            
            showNotification('已创建新对话');
        }
    } catch (error) {
        showError('创建新对话失败: ' + error.message);
    }
}

// 发送消息
async function sendMessage() {
    const message = messageInput.value.trim();
    if (!message) return;
    
    if (!currentSessionId) {
        showError('请先创建或选择一个会话');
        return;
    }
    
    // 添加用户消息到界面
    addMessage(message, 'user');
    
    // 清空输入框并重置高度
    messageInput.value = '';
    messageInput.style.height = '48px';
    
    // 显示加载状态
    const loadingMessage = addLoadingMessage();
    
    try {
        // 调用AI对话API
        const response = await ChatAPI.chat(message, currentSessionId);
        
        if (response.code === 200) {
            // 移除加载消息
            loadingMessage.remove();
            
            // 添加AI回复
            addMessage(response.data.response, 'ai');
            
            // 更新会话列表
            await loadSessions();
        }
    } catch (error) {
        // 移除加载消息
        loadingMessage.remove();
        
        // 显示错误消息
        addMessage('抱歉，我遇到了一些问题，请稍后再试。', 'ai');
        showError('发送消息失败: ' + error.message);
    }
}

// 添加消息到界面
function addMessage(text, sender, timestamp = null) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}-message`;
    
    const avatar = document.createElement('div');
    avatar.className = 'message-avatar';
    
    if (sender === 'ai') {
        avatar.innerHTML = '<i class="fas fa-user-md"></i>';
    } else {
        avatar.innerHTML = '<i class="fas fa-user"></i>';
    }
    
    const content = document.createElement('div');
    content.className = 'message-content';
    
    const messageText = document.createElement('div');
    messageText.className = 'message-text';
    
    // 处理多行文本
    const lines = text.split('\n');
    lines.forEach((line, index) => {
        const p = document.createElement('p');
        p.textContent = line;
        messageText.appendChild(p);
    });
    
    const messageTime = document.createElement('div');
    messageTime.className = 'message-time';
    messageTime.textContent = timestamp ? formatTime(timestamp) : getCurrentTime();
    
    content.appendChild(messageText);
    content.appendChild(messageTime);
    
    messageDiv.appendChild(avatar);
    messageDiv.appendChild(content);
    
    chatMessages.appendChild(messageDiv);
    
    // 滚动到底部
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 添加加载消息
function addLoadingMessage() {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message ai-message loading-message';
    
    const avatar = document.createElement('div');
    avatar.className = 'message-avatar';
    avatar.innerHTML = '<i class="fas fa-user-md"></i>';
    
    const content = document.createElement('div');
    content.className = 'message-content';
    
    const messageText = document.createElement('div');
    messageText.className = 'message-text loading';
    messageText.innerHTML = '<div class="loading-dots"><span></span><span></span><span></span></div>';
    
    content.appendChild(messageText);
    
    messageDiv.appendChild(avatar);
    messageDiv.appendChild(content);
    
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    return messageDiv;
}

// 删除会话
async function deleteSession(sessionId) {
    if (!confirm('确定要删除这个会话吗？')) {
        return;
    }
    
    try {
        const response = await SessionAPI.deleteSession(sessionId);
        
        if (response.code === 200) {
            // 从列表中移除
            sessions = sessions.filter(s => s.session_id !== sessionId);
            
            // 如果删除的是当前会话，清空聊天界面
            if (sessionId === currentSessionId) {
                currentSessionId = null;
                chatMessages.innerHTML = '';
            }
            
            // 更新UI
            renderSessionsList();
            
            showNotification('会话已删除');
        }
    } catch (error) {
        showError('删除会话失败: ' + error.message);
    }
}

// 查看记忆
async function viewMemory() {
    if (!currentSessionId) {
        showNotification('请先选择一个会话');
        return;
    }
    
    try {
        const response = await HistoryAPI.getSessionStatistics(currentSessionId);
        
        if (response.code === 200) {
            const stats = response.data;
            const memoryText = `会话标题: ${stats.title}\n创建时间: ${formatTime(stats.created_at)}\n对话数量: ${stats.conversation_count}\n平均处理时间: ${stats.avg_processing_time}秒`;
            
            alert(`会话记忆：\n\n${memoryText}`);
        }
    } catch (error) {
        showError('获取记忆失败: ' + error.message);
    }
}

// 清空记忆
async function clearMemory() {
    if (!currentSessionId) {
        showNotification('请先选择一个会话');
        return;
    }
    
    if (confirm('确定要清空当前会话的所有对话吗？')) {
        try {
            // 这里可以调用后端API清空会话，或者直接清空前端显示
            chatMessages.innerHTML = '';
            currentConversations = [];
            
            // 添加欢迎消息
            addMessage("Hi, 你好\n我是你的AI助手,有什么可以帮助你的吗?", 'ai');
            
            showNotification('记忆已清空');
        } catch (error) {
            showError('清空记忆失败: ' + error.message);
        }
    }
}

// 工具函数
function getCurrentTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
}

function formatTime(timestamp) {
    const date = new Date(timestamp);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
}

function showNotification(message) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #667eea;
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        font-size: 14px;
        z-index: 1000;
        animation: slideIn 0.3s ease;
    `;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

function showError(message) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #ef4444;
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        font-size: 14px;
        z-index: 1000;
        animation: slideIn 0.3s ease;
    `;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 5000);
}

function showLoading(container) {
    container.innerHTML = '<div class="loading">加载中...</div>';
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .session-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;
        margin-bottom: 8px;
    }
    
    .session-item:hover {
        background-color: #f1f5f9;
    }
    
    .session-item.active {
        background-color: #e0e7ff;
        border: 1px solid #667eea;
    }
    
    .session-info {
        flex: 1;
    }
    
    .session-title {
        font-size: 13px;
        font-weight: 500;
        color: #1e293b;
        margin-bottom: 2px;
    }
    
    .session-time {
        font-size: 11px;
        color: #64748b;
    }
    
    .delete-session-btn {
        background: none;
        border: none;
        color: #94a3b8;
        cursor: pointer;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.2s ease;
    }
    
    .delete-session-btn:hover {
        background-color: #fecaca;
        color: #dc2626;
    }
    
    .loading-dots {
        display: flex;
        gap: 4px;
        align-items: center;
    }
    
    .loading-dots span {
        width: 6px;
        height: 6px;
        background-color: #94a3b8;
        border-radius: 50%;
        animation: bounce 1.4s infinite ease-in-out;
    }
    
    .loading-dots span:nth-child(1) { animation-delay: -0.32s; }
    .loading-dots span:nth-child(2) { animation-delay: -0.16s; }
    
    @keyframes bounce {
        0%, 80%, 100% {
            transform: scale(0);
        }
        40% {
            transform: scale(1);
        }
    }
    
    .loading {
        text-align: center;
        color: #64748b;
        font-size: 13px;
        padding: 20px;
    }
`;
document.head.appendChild(style);

// 自动调整textarea高度
function autoResizeTextarea() {
    const textarea = this;
    textarea.style.height = 'auto';
    const newHeight = Math.min(textarea.scrollHeight, 120);
    textarea.style.height = newHeight + 'px';
}

// 处理键盘事件
function handleKeyDown(e) {
    // Enter键发送消息（除非按住Shift键换行）
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
    
    // Ctrl/Cmd + Enter 发送消息
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        sendMessage();
    }
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + N 新建对话
    if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
        e.preventDefault();
        createNewChat();
    }
}); 